package org.compiere.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

public class Mhrmworktime extends X_hrm_worktime {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3837155464853315381L;
	
	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (Mhrmworktime.class);
	
	
	public Mhrmworktime(Properties ctx, int hrm_worktime_ID, String trxName) {
		super(ctx, hrm_worktime_ID, trxName);
	}

	public Mhrmworktime(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}
	
	/** Select work days for HRM Salary Employee */
	public static int getWorkDays(int hrm_shedulerule_id, Timestamp dt){
		
		if(hrm_shedulerule_id == 0)
    		return 0;
				
		int result = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// Employee data from the card
		String sql_ = "SELECT DAYS FROM HRM_WORKTIME_V " +
						"WHERE AD_CLIENT_ID=? " +
						"AND HRM_SHEDULERULE_ID=? " +
						"AND TO_DATE('01-'||TO_CHAR(DATEFROM,'MM-YYYY'),'DD-MM-YYYY') <= ? " +
						"AND TO_DATE('31-'||TO_CHAR(DATEFROM,'MM-YYYY'),'DD-MM-YYYY') >= ? " ;
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			pstmt.setInt(1, Env.getAD_Client_ID(Env.getCtx()));
			pstmt.setInt(2, hrm_shedulerule_id);
			pstmt.setTimestamp(3, dt);
			pstmt.setTimestamp(4, dt);
			
			rs = pstmt.executeQuery();
			if(rs.next())
				return rs.getInt(1);		
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}

		return result;
	}
	
	/** Select work hour for HRM Salary Employee */
	public static int getWorkHours(int hrm_shedulerule_id, Timestamp dt){
		
		if(hrm_shedulerule_id == 0)
    		return 0;
				
		int result = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// Employee data from the card
		String sql_ = "SELECT HOURS FROM HRM_WORKTIME_V \n" +
						"WHERE AD_CLIENT_ID=" + Env.getAD_Client_ID(Env.getCtx()) + " \n" +
						"AND HRM_SHEDULERULE_ID=" + hrm_shedulerule_id + " \n" +
						" AND " + DB.TO_DATE(dt) + " BETWEEN date_trunc('MONTH'::text, DATEFROM) " +
						" AND (date_trunc('MONTH'::text, DATEFROM) + '1 mon'::interval - '1 day'::interval)";
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			rs = pstmt.executeQuery();
			if(rs.next())
				return rs.getInt(1);		
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}

		return result;
	}

}
